<template>
  <a-spin :spinning="props.loading || loading">
    <div class="course-list">
      <div v-for="item in props.data" :key="item.id" class="course-item">
        <img :src="item.cover" class="course-cover" />
        <div class="course-info">
          <h4>辅导课程：{{ item.title }}</h4>
          <div class="meta">
            <span>教师：{{ item.teacherName }}</span>
            <span>时间：{{ dayjs(item.startTime).format('YYYY-MM-DD ') }} - {{ dayjs(item.endTime).format('YYYY-MM-DD')
            }}</span>
            <span>电话：{{ item.mobile }}</span>
            <span>状态：{{ statusMap[item.status] }}</span>
          </div>
          <div class="actions" style="margin-left: auto; margin-top: auto">
            <a-button v-if="item.status === 'PENDING'" @click="cancelCourse(item.id)">取消预约</a-button>
            <template v-if="item.status === 'PROGRESS'">
              <a-button v-if="!item.studentConfirmed" type="primary" @click="studentConfirm(item.id)">确认完成</a-button>
              <a-tag v-else color="green" style="margin-left:8px">✓ 已确认，待教师确认</a-tag>
            </template>
            <template v-if="item.status === 'COMPLETED'">
              <a-button v-if="!item.hasEvaluation" type="primary" @click="showEvaluationModal(item.id)">立即评价</a-button>
              <a-tag v-else color="blue">已评价</a-tag>
            </template>
          </div>
        </div>
      </div>
      <a-empty v-if="props.data.length === 0" description="暂无课程" />
    </div>
  </a-spin>
  <a-modal title="课程评价" :visible="showEvaluation" :footer="null" @cancel="closeEvaluation">
    <a-form :model="evaluationForm" @finish="submitEvaluation">
      <a-form-item label="课程评分" required>
        <a-rate v-model:value="evaluationForm.score" />
      </a-form-item>
      <a-form-item label="评价内容">
        <a-textarea v-model:value="evaluationForm.comment" :rows="4" placeholder="请输入您的课程体验（可选）" :maxlength="500" />
      </a-form-item>
      <a-form-item class="submit-button-item">
        <a-button type="primary" html-type="submit" :loading="submitting">
          提交评价
        </a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message, Modal } from 'ant-design-vue';
import { listMyCoursesApi, cancelCourseApi, completeCourseApi, CourseStatus } from '/@/api/course';
import { useUserStore } from '/@/store';
import { onMounted } from 'vue';
import { BASE_URL } from '/@/store/constants';
import dayjs from 'dayjs';
import request from "/@/utils/http/axios";
import { submitEvaluationApi } from '/@/api/course';


const loading = ref(false);
const userStore = useUserStore();
const userId = userStore.user_id; // 获取当前用户ID
// const data = ref<Course[]>([]);

// onMounted(() => {
//   loadCourses(); // [!code focus]
// });
const showEvaluation = ref(false);
const submitting = ref(false);
const currentCourseId = ref<number>();
const evaluationForm = reactive({
  score: 5,
  comment: '',
});

const showEvaluationModal = (courseId: number) => {
  currentCourseId.value = courseId;
  showEvaluation.value = true;
};

const closeEvaluation = () => {
  showEvaluation.value = false;
  evaluationForm.score = 5;
  evaluationForm.comment = '';
};

const submitEvaluation = async () => {
  if (!evaluationForm.score) {
    message.error('请选择评分');
    return;
  }

  submitting.value = true;
  try {
    await submitEvaluationApi(
      {
        courseId: currentCourseId.value!,
        score: evaluationForm.score,
        comment: evaluationForm.comment,
      },
      userStore.user_id // 传递当前用户ID
    );
    message.success('评价提交成功');
    closeEvaluation();
    emit('refresh');
  } catch (error) {
    message.error('评价提交失败');
  } finally {
    submitting.value = false;
  }
};

// 定义课程数据类型
interface Course {
  id: number;
  title: string;
  cover: string;
  teacherName: string;
  startTime: string;
  endTime: string;
  mobile: string;
  status: 'PENDING' | 'PROGRESS' | 'COMPLETED' | 'CANCELED';
  studentConfirmed: boolean;
  hasEvaluation?: boolean;
}

// 定义组件 Props
const props = defineProps<{
  data: Course[];
  loading?: boolean;
}>();

const data = ref<Course[]>(props.data);

// 定义事件
const emit = defineEmits<{
  (event: 'refresh'): void;
}>();

// 状态映射
const statusMap = {
  PENDING: '待教师确认',
  PROGRESS: '进行中',
  COMPLETED: '已结束',
  CANCELED: '已取消',
};


// 获取课程列表时传递 userId 和状态
// const loadCourses = async (status?: CourseStatus) => {
//   try {
//     const userId = userStore.user_id;
//     const courses = await listMyCoursesApi(userId, status);
//     data.value = courses.map(course => ({
//       ...course,
//       cover: `${BASE_URL}/api/staticfiles/image/${course.cover}`
//     }));
//   } catch (error) {
//     message.error('获取课程失败');
//   }
// };

// 取消课程
const cancelCourse = async (id: number) => {
  Modal.confirm({
    title: '确认取消课程吗？',
    onOk: async () => {
      loading.value = true; // 开启本地加载状态
      try {
        await cancelCourseApi(id, userId);
        message.success('已取消');
        emit('refresh');
      } finally {
        loading.value = false; // 关闭本地加载状态
      }
    },
  });
};

// 确认课程完成
const confirmComplete = async (id: number) => {
  Modal.confirm({
    title: '确认课程已完成吗？',
    onOk: async () => {
      loading.value = true;
      try {
        await completeCourseApi(id, userId);
        message.success('已确认完成');
        emit('refresh');
      } finally {
        loading.value = false;
      }
    },
  });
};

const studentConfirm = async (courseId: number) => {
  try {
    await request({
      method: 'post',
      url: `/api/course/studentConfirm/${courseId}`,
      params: { userId: userStore.user_id }
    });
    message.success('确认成功');
    emit('refresh'); // 触发父组件刷新
  } catch (error) {
    message.error('确认失败');
  }
};
</script>

<style scoped lang="less">
.course-list {
  max-height: 500px;
  overflow-y: auto;

  .course-item {
    display: flex;
    padding: 16px;
    border-bottom: 1px solid #eee;

    .course-cover {
      width: 120px;
      height: 130px;
      object-fit: cover;
      margin-right: 16px;
    }

    .course-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      h4 {
        margin: 0 0 8px;
        color: #152844;
      }

      .meta {
        color: #666;

        span {
          display: block;
          margin-bottom: 4px;
        }
      }

      .actions {
        margin-top: auto; // 自动顶边距
        margin-left: auto; // 自动左边距
        display: flex;
        gap: 8px; // 按钮间距替代margin-right
      }
    }
  }
}

.submit-button-item {
  text-align: center; 
}
</style>